export default {
  bind(el, binding, vnode) {
    // 获取拖拽目标元素，默认为当前元素，也可以通过value指定
    const targetEl = binding.value?.target ? el.querySelector(binding.value.target) : el;
    if (!targetEl) return;

    // 鼠标按下时的位置
    let startX = 0;
    let startY = 0;
    // 元素的初始位置
    let initialX = 0;
    let initialY = 0;
    // 是否正在拖拽
    let isDragging = false;

    // 鼠标按下事件处理函数
    function handleMouseDown(e) {
      if (binding.value?.handle) {
        // 如果指定了handle，只允许handle区域触发拖拽
        const handleEl = el.querySelector(binding.value.handle);
        if (!handleEl?.contains(e.target)) return;
      }

      isDragging = true;
      startX = e.clientX;
      startY = e.clientY;

      // 获取元素当前位置
      const transform = window.getComputedStyle(el).transform;
      if (transform && transform !== 'none') {
        const matrix = new DOMMatrix(transform);
        initialX = matrix.m41;
        initialY = matrix.m42;
      } else {
        initialX = 0;
        initialY = 0;
      }

      // 添加事件监听
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }

    // 鼠标移动事件处理函数
    function handleMouseMove(e) {
      if (!isDragging) return;

      e.preventDefault();
      
      // 计算移动距离
      const deltaX = e.clientX - startX;
      const deltaY = e.clientY - startY;

      // 更新元素位置
      el.style.transform = `translate(${initialX + deltaX}px, ${initialY + deltaY}px)`;
    }

    // 鼠标松开事件处理函数
    function handleMouseUp() {
      isDragging = false;
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    }

    // 添加鼠标按下事件监听
    targetEl.addEventListener('mousedown', handleMouseDown);

    // 保存事件处理函数，以便在unbind时移除
    el._draggable = {
      targetEl,
      handleMouseDown
    };
  },

  unbind(el) {
    if (el._draggable) {
      const { targetEl, handleMouseDown } = el._draggable;
      targetEl.removeEventListener('mousedown', handleMouseDown);
      delete el._draggable;
    }
  }
}; 